/**
 * 
 */
package gapidt.plugin.actions;

import gapidt.plugin.AnalysisResultsManager;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.log4j.Logger;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

/**
 * @author diegopiu
 * 
 */
public class AnalyzeAllProjects implements IWorkbenchWindowActionDelegate {

	static Logger logger = Logger.getLogger(AnalyzeFromEditor.class);

	IProject iProject = null;

	IWorkbenchWindow activeWindow = null;

	@Override
	public void run(IAction iAction) {
		long tiempoInicio = System.currentTimeMillis();
		IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();

		AnalysisResultsManager.getInstance().clearResults();
		
		for (IProject iProject : projects) {
			if (!iProject.isHidden() && iProject.isOpen()) {
				System.out.println("Proyecto: " + iProject.getName());
				IJavaProject javaProject = JavaCore.create(iProject);

				IFile file = iProject.getFile("/ServiceLocation.xml");

				if (file.exists()) {
					try {
						InputStream inputStream = file.getContents();
						NodeList nodeList = getServiceIFPath(inputStream);

						for (int i = 0; i < nodeList.getLength(); i++) {
							String pattern = nodeList.item(i).getTextContent()
									.replaceFirst("build/", "")
									.replace(".class", ".java");

							for (IPackageFragment iPackageFragment : javaProject.getPackageFragments()) {

								for (ICompilationUnit iCompilationUnit : iPackageFragment.getCompilationUnits()) {

									String path = iCompilationUnit.getPath().toString();
									if (path.contains(pattern)) {
										AnalysisResultsManager.getInstance().analyzeElement(iCompilationUnit, null);
									}
								}
							}
						}
					} catch (CoreException ce) {
						ce.printStackTrace();
					}
				}
			}
		}
		long totalTiempo = (System.currentTimeMillis() - tiempoInicio) / 1000;
		System.out.println("El tiempo de análisis es :" + totalTiempo + " seg");
	}

	@Override
	public void selectionChanged(IAction arg0, ISelection arg1) {
		// TODO Auto-generated method stub
	}

	@Override
	public void dispose() {
		// TODO Auto-generated method stub
	}

	@Override
	public void init(IWorkbenchWindow workbenchWindow) {
		activeWindow = workbenchWindow;
	}

	private NodeList getServiceIFPath(InputStream inputStream) {

		try {
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
			Document document = docBuilder.parse(inputStream);

			document.getDocumentElement().normalize();

			NodeList nodeList = document.getElementsByTagName("serviceIFPath");

			return nodeList;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
